package com.example.lending.ViewModel.Repository;

import android.content.Context;
import android.os.AsyncTask;
import android.provider.ContactsContract;

import androidx.lifecycle.LiveData;
import androidx.room.Delete;
import androidx.room.Update;

import com.example.lending.Model.Book;
import com.example.lending.Model.Dao.BookDao;
import com.example.lending.Model.Database;

import java.util.List;

public class BookReposity {
    private LiveData<List<Book>>allBookLive;
    private BookDao bookDao;

    public LiveData<List<Book>> getAllBookLive(){return allBookLive;}
    public LiveData<List<Book>>findBookWithPattern(String pattern){
        return bookDao.findBookWithPattern("%"+pattern+"%");
    }

    public BookReposity(Context context){
        Database bookDatabase = Database.getDatabase(context.getApplicationContext());
        bookDao=bookDatabase.getBookDao();
        allBookLive = bookDao.getAllBookLive();
    }
    public void insertBooks(Book... books){
        new InsertAsyncTask(bookDao).execute(books);
    }
    public void updataBooks(Book... books){
        new UpdataAsyncTask(bookDao).execute(books);
    }
    public void deleteBooks(Book... books){
        new InsertAsyncTask(bookDao).execute(books);
    }
    public void deleteAllBooks(Book... books){
        new DeleteAllAsyncTask(bookDao).execute();
    }

    static class InsertAsyncTask extends AsyncTask<Book,Void,Void>{
        private BookDao bookDao;
        public InsertAsyncTask(BookDao bookDao) {
            this.bookDao = bookDao;
        }

        @Override
        protected Void doInBackground(Book... books) {
            bookDao.insertBook(books);
            return null;
        }
    }
    static class UpdataAsyncTask extends AsyncTask<Book,Void,Void>{
        private BookDao bookDao;
        public UpdataAsyncTask(BookDao bookDao) {
            this.bookDao = bookDao;
        }

        @Override
        protected Void doInBackground(Book... books) {
            bookDao.updataBook(books);
            return null;
        }
    }
    static class DeleteAsyncTask extends AsyncTask<Book,Void,Void>{
        private BookDao bookDao;
        public DeleteAsyncTask(BookDao bookDao) {
            this.bookDao = bookDao;
        }

        @Override
        protected Void doInBackground(Book... books) {
            bookDao.deleteBook(books);
            return null;
        }
    }
    static class DeleteAllAsyncTask extends AsyncTask<Void,Void,Void>{
        private BookDao bookDao;
        public DeleteAllAsyncTask(BookDao bookDao) {
            this.bookDao = bookDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            bookDao.deleteAllBook();
            return null;
        }
    }
}
